# coding: utf8
class JsonEncoder(object):
    def __init__(self, db):
        self.db = db

    def encode_all(self, x):
        pass

    def encode(self, m):
        if self.check_is_model(m):
            return self.encode_model(m)
        elif self.check_is_list(m):
            return self.encode_list(m)
        else:
            return self.encode_normal(m)

    def encode_normal(self, m):
        if self.check_is_dict(m):
            o = dict()
            keys = m.keys()
            for _ in keys:
                o[_] = self.encode(m[_])
            return o
        else:
            return m

    def encode_model(self, m):
        o = dict()
        col_name_list = m._sa_instance_state.attrs.items()
        for _ in col_name_list:
            k, _v = _
            v = getattr(m, k, None)
            if self.check_is_model(v):
                o[k] = self.encode_model(v)
            elif self.check_is_list(v):
                o[k] = self.encode_list(v)
            else:
                o[k] = v

        return o

    def encode_list(self, ls):
        arr = []
        for _ in ls:
            arr.append(self.encode(_))
        return arr

    def check_is_list(self, m):
        return isinstance(m, list)

    def check_is_model(self, m):
        return isinstance(m, self.db.Model)

    def check_is_dict(self, m):
        return isinstance(m, dict)
